package com.jsmile.cloud.msgcenter.pay.model;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.jsmile.cloud.msgcenter.api.constants.MsgConstants;
import com.jsmile.cloud.msgcenter.api.enums.PayStatusEnum;
import com.jsmile.cloud.msgcenter.api.req.ReqPayOrderCreate;
import com.jsmile.cloud.msgcenter.api.req.ReqPayOrderSuccess;
import com.jsmile.cloud.msgcenter.pay.event.PayOrderSuccessEvent;
import com.jsmile.cloud.tradecenter.api.req.ReqPayOrder;
import com.jsmile.mail.security.event.DomainEventPublisher;
import com.jsmile.mall.api.exception.ExceptionKit;

import cn.hutool.core.util.IdUtil;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

/**
 * @author 龚亮
 * @version 1.0
 * @desc 为了薪资破万，还是睡一会儿吧...!
 * @date 2020年06月07日 11:19:01
 */
@ApiModel
@Data
@TableName("t_ac_pay_order")
public class PayOrderInfo extends Model<PayOrderInfo> {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "主键id")
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;
    @ApiModelProperty(value = "用户id")
    private Long userId;
    @ApiModelProperty(value = "微信openid")
    private String openId;
    @ApiModelProperty(value = "支付appid")
    private String payAppId;
    @ApiModelProperty(value = "支付商户号")
    private String mchId;
    @ApiModelProperty(value = "子商户号（支付宝或微信）")
    private String subMchId;
    @ApiModelProperty(value = "微信或者支付宝的订单号")
    private String mchOrderNo;
    @ApiModelProperty(value = "商户订单号")
    private String outTradeNo;
    @ApiModelProperty(value = "第三方交易流水号")
    private String thirdPayNo;
    @ApiModelProperty(value = "交易类型 （充值、消费）")
    private Integer tradeType;
    @ApiModelProperty(value = "1创建（待支付) 2支付完成 3支付失败 ")
    private Integer payStatus;
    @ApiModelProperty(value = "付款码")
    private String authCode;
    @ApiModelProperty(value = "支付宝授权token")
    private String authToken;
    @ApiModelProperty(value = "支付类型")
    private Integer payType;
    @ApiModelProperty(value = "支付金额 最小单位:分")
    private Long payAmount;
    @ApiModelProperty(value = "描述")
    private String remark;
    @ApiModelProperty(value = "扩展字段 JSON格式串")
    private String extraParams;
    @ApiModelProperty(value = "创建时间")
    private Date createTime;
    @ApiModelProperty(value = "支付时间")
    private Date payTime;
    @ApiModelProperty(value = "update_time")
    private Date updateTime;
    @ApiModelProperty(value = "订单编号")
    private Long orderNo;
    @ApiModelProperty(value = "平台id")
    private Integer platformId;
    @ApiModelProperty(value = "业务id")
    private Integer bizCode;
    @ApiModelProperty(value = "描述")
    private String payTitle;
    @ApiModelProperty(value = "描述")
    private String payDetial;
    @ApiModelProperty(value = "ip地址")
    private String ip;
    @ApiModelProperty(value = "商户id")
    private Long tenantId;

    public static List<PayOrderInfo> create(ReqPayOrderCreate reqPayOrderCreate, PayInfo payInfo) {
        return reqPayOrderCreate.getPayOrderInfos().stream().map(x -> {
            PayOrderInfo payOrder = new PayOrderInfo();
            payOrder.setCreateTime(new Date());
            payOrder.setUpdateTime(new Date());
            payOrder.setOrderNo(x.getOrderNo());
            payOrder.setPayAmount(x.getActuallyPayAmount());
            payOrder.setUserId(reqPayOrderCreate.getCurUserId());
            payOrder.setPayType(reqPayOrderCreate.getPayType());
            payOrder.setTenantId(reqPayOrderCreate.getCurTenantId());
            payOrder.setPayTitle(x.getTitle());
            payOrder.setPayDetial(StringUtils.deleteWhitespace(x.getDetial()));
            payOrder.setIp(reqPayOrderCreate.getIp());
            payOrder.setPayAppId(payInfo.getAppId());
            payOrder.setMchId(payInfo.getMchId());
            payOrder.setOpenId(reqPayOrderCreate.getOpenId());
            return payOrder;
        }).collect(Collectors.toList());
    }

    // 支付完成更新微信或者支付宝的订单号
    public static void paySuccess(ReqPayOrderSuccess reqPayOrderSuccess, List<PayOrderInfo> payOrders) {
        payOrders.forEach(x -> {
            x.setPayTime(new Date());
            x.setMchOrderNo(reqPayOrderSuccess.getMchOrderNo());
            x.setPayStatus(PayStatusEnum.SUCCESS.getValue());
        });
        DomainEventPublisher.publish(new PayOrderSuccessEvent(payOrders));
    }

    // 去支付
    public static void pay(ReqPayOrder reqPayOrder, List<PayOrderInfo> payOrders) {
        final String outTradeNo = IdUtil.getSnowflake(MsgConstants.SNOWFLAKE.workerId, MsgConstants.SNOWFLAKE.datacenterId).nextId() + "";
        payOrders.forEach(x -> {
            ExceptionKit.checkArgument(PayStatusEnum.SUCCESS.getValue() == x.getPayStatus(), "已支付的订单不能重新支付");
            x.setPayType(reqPayOrder.getPayType());
            x.setUpdateTime(new Date());
            x.setOutTradeNo(outTradeNo);
        });
    }
}
